import argparse
import json
import time
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 从外部配置文件读取用户信息的函数
def read_user_info(file_path):
    try:
        with open(file_path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"用户信息配置文件 {file_path} 未找到，请检查文件路径！")
        return {}
    except json.JSONDecodeError:
        print(f"用户信息配置文件 {file_path} 格式有误，请检查文件内容是否符合JSON格式！")
        return {}


def clear_cookies(driver):
    try:
        driver.delete_all_cookies()
    except Exception as e:
        print(f"清除Cookies时出现错误: {e}")


def fill_form(driver, user_info):
    try:
        # 滚动页面到最底部，确保所有元素加载（可根据实际情况调整此逻辑）
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # 提取元素定位选择器到变量，方便后续维护修改
        field_selector = 'div.field'
        topichtml_selector = '.topichtml'
        input_selector = 'input'

        # 使用显示等待确保元素出现
        wait = WebDriverWait(driver, 10)
        field_elements = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, field_selector)))

        for field in field_elements:
            question_text = field.find_element(By.CSS_SELECTOR, topichtml_selector).text
            result = ""
            for key in user_info:
                if key in question_text:
                    result += user_info[key]
            input_element = field.find_element(By.CSS_SELECTOR, input_selector)
            input_element.send_keys(result)
    except Exception as e:
        print(f"填写表单时出现错误: {e}")


def main():
    parser = argparse.ArgumentParser(description='自动化参与活动程序')
    parser.add_argument('url', type=str, help='活动页面网址')
    parser.add_argument('driver_path', type=str, help='Chrome驱动程序路径')
    parser.add_argument('user_info_file', type=str, help='用户信息配置文件（JSON格式）路径')
    parser.add_argument('target_time', type=str, help='程序启动目标时间，格式为 "YYYY-MM-DD HH:MM:SS"')
    args = parser.parse_args()

    user_info = read_user_info(args.user_info_file)
    if not user_info:
        return

    try:
        service = Service(args.driver_path)
        driver = webdriver.Chrome(service=service)

        driver.get(args.url)

        clear_cookies(driver)
        fill_form(driver, user_info)

        # 假设提交按钮的CSS选择器为 #submit_btn，可根据实际页面修改
        submit_selector = '#ctlNext'
        submit_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, submit_selector)))
        submit_button.click()

        time.sleep(30)
        driver.quit()
    except Exception as e:
        print(f"程序运行出现错误: {e}")


if __name__ == "__main__":
    print("程序即将按设定时间运行")
    try:
        args = argparse.ArgumentParser().parse_args()
        target_time = datetime.strptime(args.target_time, "%Y-%m-%d %H:%M:%S")
        now = datetime.now()
        wait_time = (target_time - now).total_seconds()
        if wait_time > 0:
            while wait_time > 0:
                print(f"还需等待 {timedelta(seconds=wait_time)} 后启动程序，请耐心等待...")
                time.sleep(min(60, wait_time))  # 每次最多等待1分钟，避免长时间无响应的感觉
                wait_time = (target_time - datetime.now()).total_seconds()
        main()
    except ValueError:
        print("输入的时间格式不正确，请按照 'YYYY-MM-DD HH:MM:SS' 的格式输入目标时间")
